import React, { Component } from 'react'
import {
  View,
  StyleSheet,
  ScrollView,
  Image,
  Text,
  TouchableOpacity,
  FlatList,
  ActivityIndicator,
  SafeAreaView,
  RefreshControl
} from 'react-native'

import NavBar from '../../../components/PublicHeader';
import {
  GET_USER_APPBROWSE,
  DELETE_USER_APPBROWSE
} from '../../../public/WebApi/mailListApi';
import fetchWebApi from '../../../public/WebApi/fetchBase';
import getStorageValue from '../../../utils/getStorageValue';
import { Constant } from '../../../public/js/constant';
import Loading from '../../../components/Loading';


export default class seenme extends Component {
  constructor(props) {
    super(props)
    this.state = {
      seenmeList: [],
      page: 0,
      tempAddDatas: [],
      isLoading: false,
      pieces: 10,
      status: 1,
      upTime: 0,
      createTime: null,
      isRefreshing: false,
      flag: false
    }
  }

  componentDidMount = () => {
    Loading.show()
    this.getAppbrowse()

  }
  // 获取时分秒
  getLocalTime(date) {
    var date = new Date(date);//如果date为13位不需要乘1000

    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';

    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';

    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());

    return h + m + s;//Y + M + D +
  }
  // 获取月日
  getLocalTime2(date) {
    var date = new Date(date);//如果date为13位不需要乘1000

    var Y = date.getFullYear() + '年';

    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';

    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日';
    return M + D
  }

  getdata(date) {
    return this.getLocalTime2(date)
  }

  async getAppbrowse() {
    const res = await fetchWebApi(GET_USER_APPBROWSE,
      {
        token: await getStorageValue(Constant.TOKEN),
        page: this.state.page, pieces: this.state.pieces
      }, 'POST')
    // console.log("######### getAppbrowse");
    // console.log("111111111111111111111");
    // console.log(res)

    if (res.status == 200) {
      if (res.data == '') {
        this.setState({
          flag: true
        })
      }
      if (this.state.page == 0) {
        this.setState({
          seenmeList: res.data,
        })
        Loading.hide()
      } else {
        console.log(res.data.length === 0)
        this.setState({
          tempAddDatas: res.data
        })
        Loading.hide()
      }
      if (res.data.length == 0) {
        this.setState({
          status: 0
        })
        Loading.hide()
      }
    }
  }

  // 加载数据
  genIndicator() {
    return <View style={styles.IndicatorContainer}>
      <ActivityIndicator  //显示一个圆形的 loading 提示符号。
        style={styles.Indicator}
        size={"small"}
        animating={true}
        color={'gray'}
      />
      <Text>正在加载更多</Text>
    </View>
  }

  handleRefresh = () => {
    this.setState({
      isRefreshing: true,//tag,下拉刷新中，加载完全，就设置成flase
      seenmeList: [],
      page: 0
    });
    this.getAppbrowse()
    this.setState({
      isRefreshing: false
    })
  }

  async remove() {
    const res = await fetchWebApi(DELETE_USER_APPBROWSE,
      { token: await getStorageValue(Constant.TOKEN) }, 'POST')

    if (res.status == 200) {
      console.log("清空成功")
      this.setState({
        seenmeList: [],
        tempAddDatas: []

      })
      this.getAppbrowse()
    }
  }

  // 页数加一，向页面添加一页数据
  loadData(pullUp) {
    this.setState({
      page: this.state.page + this.state.pieces,
    })
    this.getAppbrowse();
    setTimeout(() => {
      var dataArray = []
      if (pullUp) {

        dataArray = this.state.seenmeList
        dataArray = [...this.state.seenmeList, ...this.state.tempAddDatas]
      }
      this.setState({
        seenmeList: dataArray,
        isLoading: false,
      })

    }, 1000);
  }


  render() {
    let upTime = 0
    // flatlist 数据循环列表
    const Item = ({ item, index }) => {
      // console.log("究竟多少个");
      // console.log(item.createTime);
      // console.log("这个是对比的");
      // // console.log(this.state.upTime);
      // console.log("对比前的");
      // console.log(this.getLocalTime2(item.createTime));
      // console.log(index)
      return (
        <View>
          {

            upTime === this.getLocalTime2(item.createTime) ?
              null
              :
              <View style={styles.title}>
                <Text>{upTime = this.getdata(item.createTime)}</Text>
              </View>
            // console.log(this.getdata(item.createTime))
          }
          <View style={styles.seenme_list}>
            <TouchableOpacity onPress={() => {
              this.props.navigation.push('introduces', {
                id: item.userInfoId,
                refresh: () => {
                  this.getAppbrowse()
                },
                remarksName: item.nickName
              })
            }}>
              <Image source={{ uri: item.avatar }} style={{ width: 50, height: 50, borderRadius: 25 }} />
            </TouchableOpacity>
            <View style={styles.list_view}>
              <Text style={styles.list_text}>{item.nickname}</Text>
              <Text style={styles.list_text2}>
                {this.getLocalTime(item.createTime)}  访问你的{item.businessId != 1 ? '社圈' : '主页'}</Text>
            </View>
          </View>
        </View>
      )
    }
    const mySocialCircle =
      <>
        {/* 底部提示 */}
        <View style={styles.bottom_container}>
          <Text style={styles.bottom_text}>没有更多了哦~</Text>
        </View>
      </>
    return (
      <View style={{ flex: 1 }}>
        <NavBar
          navigation={this.props.navigation}
          title={"谁看过我"}
          // rightImage={require('../../../assets/images/iconResources/more.png')}
          right={'清空'}
          pressRight={() => {
            this.remove()
          }}
        />
        <Loading />
        {/* 展示有谁看过我 */}
        <SafeAreaView style={{ flex: 1 }}>
          <FlatList
            showsVerticalScrollIndicator={false}
            refreshing={true}
            data={this.state.seenmeList}
            renderItem={Item}
            keyExtractor={(item, index) => String(item.createTime)}
            ListFooterComponent={() =>
              this.state.flag ? mySocialCircle : this.genIndicator()
              // mySocialCircle
              // if(){

              // }
            }//底部组件
            onEndReached={//列表被滚动到距离内容最底部不足onEndReachedThreshold设置的的距离时调用。
              () => {
                this.loadData(true);
              }
            }
            refreshControl={
              <RefreshControl
                refreshing={this.state.isRefreshing}
                onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
                colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
                progressBackgroundColor="#ffffff"
              />
            }
            onEndReachedThreshold={0.1}//0.5 表示距离内容最底部的距离为当前列表可见长度的一半时触发onEndReached回调
          />
        </SafeAreaView>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    height: 32,
    backgroundColor: 'transparent'
  },
  seenme: {
    padding: 15
  },
  seenme_list: {
    display: 'flex',
    flexDirection: 'row',
    backgroundColor: '#fff',
    padding: 15
  },
  list_view: {
    marginLeft: 15
  },
  list_text: {
    fontSize: 18
  },
  list_text2: {
    marginTop: 3,
    color: '#00000069'
  },
  IndicatorContainer: {
    alignItems: "center",
    marginTop: 20
  },
  title: {
    padding: 10
  },
  bottom_container: {
    height: 100,
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  bottom_text: {
    color: "rgba(196, 196, 196, 1)"
  },
})